from django.db import models
from django.contrib import auth
from datetime import datetime
import time


class Base(models.Model):
    """
        Base classe for Porject codes
    """
    code = models.CharField(max_length=3, db_index=True)
    description = models.CharField(max_length=120, db_index=True)
    def __unicode__(self):
        return u'%(code)s %(description)s'% {'code':self.code, 'description':self.description}
    class Meta:
        abstract = True

class Owner(Base):
    """
        Owner of the project
    """
    pass

class ProjectCode(Base):
    """
        Project Code Ownership
    """
    # owner exacly
    project_code = models.ForeignKey(Owner, null=True)
    def __unicode__(self):
        return u'%(project_code)s %(code)s %(description)s'% {'project_code': self.project_code, 'code':self.code, 'description':self.description}
    

class SubProject(Base):
    """
        Sub project  
    """
    pass

class Project(models.Model):
    """
        Project to owner
    """
    owner = models.ForeignKey(Owner)
    project_code = models.ForeignKey(ProjectCode)
    sub_project = models.ForeignKey(SubProject)
    note = models.TextField(blank=True, null=True)
    class Meta:
        unique_together = (("owner", "project_code", "sub_project"),)
    def __unicode__(self):
        return u'%(owner)s.%(project_code)s.%(sub_project)s  %(owner_description)s | %(project_description)s | %(sub_project_description)s'% {
            "owner":self.owner.code,
            "project_code": self.project_code.code, 
            "sub_project": self.sub_project.code,
            "owner_description": self.owner.description,
            "project_description": self.project_code.description,
            "sub_project_description": self.sub_project.description}
    

class DailyReport(models.Model):
    """
        The daily reports
        
        Use save_model method to assign report automaticly.
        def save_model(self, request, obj, form, change):
            obj.user = request.user
            obj.save()

    """
    date = models.DateField()
    assigned_to = models.ForeignKey(auth.models.User)
    note = models.TextField(blank=True, null=True)
    def tasks(self):
        mytasks = Task.objects.filter(daily_report=self)
        ltasks = "<ul>"
	total = 0
        for task in mytasks:
	    total = task.actual_work_hours + total
            ltasks = ltasks + "<li>" + task.name +  " " + task.note + ".  Project code: " + str(task.project_code) + " (Hours: " + str(task.actual_work_hours) + " at " + str(task.start_time) + ")</li>"
        ltasks = ltasks + "</ul>"
	ltasks = ltasks + "<p><b>Total: " + self.convert_to_time(total) + "</b></p>"
        return ltasks
    tasks.allow_tags = True

    def convert_to_time(self, total):
        """
        Hour part will be converted to minutes
        """        
        try:
            mylist = str(total).split(".")
        except ValueError:
            return total
        if len(mylist) > 1:
            return "%s hours %d minutes" % (mylist[0], ((int(mylist[1])/100.00) * 60))
        else:
            return total
        
        

    	



    def __unicode__(self):
        return u'%(date)s %(assigned_to)s '% {"date":self.date, "assigned_to":self.assigned_to} 

class Task(models.Model):
    """
       Report Tasks.
    """
    name = models.CharField(max_length=120, db_index=True)
    daily_report = models.ForeignKey(DailyReport)
    start_time = models.TimeField(null=False, blank=False, default=datetime(2011, 1, 1, 8, 30, 00).time()) #default=datetime.now().time
    actual_work_hours = models.DecimalField(default=0, null=False, blank=False, max_digits=3, decimal_places=2)
    note = models.TextField(blank=True, null=True)
    project_code = models.ForeignKey(Project, blank=True, null=True)
    assigned_to = models.ForeignKey(auth.models.User)
    def date(self):
        return DailyReport.objects.get(id=self.daily_report.id).date
    date.allow_tags = True
    
    def __unicode__(self):
        return u'%(name)s'% {"name":self.name}

PRIORITY = (
           ('Very High','Very High'), 
           ('High','High'), 
           ('Normal','Normal'), 
           ('Low','Low'), 
           ('Very Low','Very Low'), 
            )

STATUS = (
          ('Complete','Complete'),
          ('Incomplete','Incomplete')
          )


class TaskNota(models.Model):
    daily_report = models.ForeignKey(DailyReport, blank=True, null=True)
    project_code = models.ForeignKey(Project, blank=True, null=True)
    name = models.CharField(max_length=120, default="New task")
    priority = models.CharField(max_length=30, choices=PRIORITY, default='Normal')
    status = models.CharField(max_length=30, choices=STATUS, default='Incomplete')
    created = models.DateTimeField(auto_now_add=True)
    completed = models.DateTimeField(blank=True, null=True)
    scheduled_for = models.DateTimeField(auto_now=True, null=True)
    estimated_hour = models.IntegerField(default=1, null=True)
    actual_work_hour = models.IntegerField(default=0, null=True)
    note = models.TextField(blank=True, null=True)        
    assigned_to = models.ForeignKey(auth.models.User)    
    def __unicode__(self):
        return u'%(priority)s %(name)s %(scheduled_for)s'% {"name":self.name, "priority":self.priority, "scheduled_for":self.scheduled_for}    
    class Meta:        
        get_latest_by = "created"
        ordering = ['-created']


    
    


